<template>
  <div class="ai-chat-container">
    <!-- 顶部导航栏 -->
    <div class="chat-header">
      <div class="header-left">
        <h2>AI 聊天助手</h2>
      </div>
    </div>

    <div class="chat-main">
      <!-- 左侧对话历史 -->
      <div class="chat-history">
        <div class="history-header">
          <h3>对话历史</h3>
          <button class="new-chat-btn" @click="startNewChat">新建对话</button>
        </div>
        <div class="history-list">
          <div
            v-for="(session, index) in chatSessions"
            :key="index"
            class="history-item"
            :class="{ active: currentSessionIndex === index }"
            @click="switchSession(index)"
          >
            <span class="session-title">对话 {{ index + 1 }}</span>
            <span class="session-time">{{ formatTime(session.timestamp) }}</span>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <div class="messages-container" ref="messagesContainer">
          <div
            v-for="(message, index) in currentSession.messages"
            :key="index"
            class="message"
            :class="{ 'user-message': message.role === 'user', 'ai-message': message.role === 'assistant' }"
          >
            <div class="message-avatar">
              <span v-if="message.role === 'user'">👤</span>
              <span v-else>🤖</span>
            </div>
            <div class="message-content">
              <!-- AI回复的思考过程 -->
              <div v-if="message.thinking" class="thinking-process">
                <div class="thinking-header">思考中...</div>
                <div class="thinking-content">{{ message.thinking }}</div>
              </div>

              <!-- 引用链接 -->
              <div v-if="message.references && message.references.length" class="references">
                <div class="references-header">参考链接:</div>
                <ul>
                  <li v-for="(ref, refIndex) in message.references" :key="refIndex">
                    <a :href="ref.url" target="_blank">{{ ref.title }}</a>
                  </li>
                </ul>
              </div>

              <!-- 最终回答 -->
              <div class="final-answer" v-html="formatMessage(message.content)"></div>

              <!-- 流式回复时的加载动画 -->
              <div v-if="message.streaming" class="streaming-indicator">
                <div class="typing-animation">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-tools">
            <!-- 模型选择器 -->
            <select v-model="selectedModel" class="model-select">
              <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
              <option value="gpt-4">GPT-4</option>
              <option value="deepseek-chat">DeepSeek Chat</option>
              <option value="claude-2">Claude 2</option>
            </select>

            <!-- 搜索模式切换按钮 -->
            <button
              class="search-mode-btn"
              :class="{ active: isSearchMode }"
              @click="toggleSearchMode"
              title="切换搜索模式"
            >
              🔍 {{ isSearchMode ? '搜索模式' : '普通模式' }}
            </button>

            <!-- 文件上传 -->
            <label class="file-upload-btn">
              <input
                type="file"
                @change="handleFileUpload"
                multiple
                accept=".txt,.pdf,.doc,.docx,.jpg,.png"
                style="display: none"
              >
              📎 上传文件
            </label>

            <!-- 已上传文件列表 -->
            <div v-if="uploadedFiles.length" class="uploaded-files">
              <span
                v-for="(file, index) in uploadedFiles"
                :key="index"
                class="file-tag"
                @click="removeFile(index)"
              >
                {{ file.name }} ×
              </span>
            </div>
          </div>

          <div class="input-container">
            <textarea
              v-model="inputMessage"
              @keydown.enter.prevent="sendMessage"
              placeholder="输入消息..."
              class="message-input"
              rows="3"
            ></textarea>
            <button
              @click="sendMessage"
              :disabled="isLoading"
              class="send-btn"
            >
              {{ isLoading ? '发送中...' : '发送' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索对话框 -->
    <div v-if="showSearch" class="search-dialog">
      <div class="search-content">
        <div class="search-header">
          <h3>搜索对话</h3>
          <button class="close-btn" @click="toggleSearch">×</button>
        </div>
        <input
          v-model="searchQuery"
          placeholder="输入关键词搜索..."
          class="search-input"
        >
        <div class="search-results">
          <div
            v-for="(result, index) in searchResults"
            :key="index"
            class="search-result-item"
            @click="navigateToMessage(result.sessionIndex, result.messageIndex)"
          >
            <div class="result-preview">{{ result.preview }}</div>
            <div class="result-meta">对话 {{ result.sessionIndex + 1 }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'AiChat',
  data() {
    return {
      selectedModel: 'deepseek-v12',
      inputMessage: '',
      isLoading: false,
      showSearch: false,
      searchQuery: '',
      uploadedFiles: [],
      currentSessionIndex: 0,
      chatSessions: [
        {
          timestamp: new Date(),
          messages: []
        }
      ],
      eventSource: null,
      searchResults: [],
      isSearchMode: false // 搜索模式状态
    }
  },
  computed: {
    currentSession() {
      return this.chatSessions[this.currentSessionIndex];
    }
  },
  methods: {
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return;

      const userMessage = {
        role: 'user',
        content: this.inputMessage,
        timestamp: new Date()
      };

      // 添加用户消息
      this.currentSession.messages.push(userMessage);

      // 添加AI消息占位符
      const aiMessage = {
        role: 'assistant',
        content: '',
        thinking: '',
        references: [],
        streaming: true,
        timestamp: new Date()
      };
      this.currentSession.messages.push(aiMessage);

      this.isLoading = true;
      this.inputMessage = '';

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });

      try {
        // 使用SSE连接后端
        this.connectSSE(userMessage.content);
      } catch (error) {
        console.error('发送消息失败:', error);
        this.isLoading = false;
        this.currentSession.messages.pop(); // 移除AI消息占位符
      }
    },

    connectSSE(message) {
      // 关闭之前的连接
      if (this.eventSource) {
        this.eventSource.close();
      }

      const apiUrl = `http://localhost:8080/api/chat/ai/generateStream/1?message=${encodeURIComponent(message)}&model=${this.selectedModel}`;


      this.eventSource = new EventSource(apiUrl);

      this.eventSource.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          const lastMessage = this.currentSession.messages[this.currentSession.messages.length - 1];

          if (data.thinking) {
            lastMessage.thinking = data.thinking;
          } else if (data.references) {
            lastMessage.references = data.references;
          } else if (data.content) {
            lastMessage.content += data.content;
          }

          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } catch (error) {
          console.error('解析SSE消息失败:', error);
        }
      };

      this.eventSource.onerror = (error) => {
        console.error('SSE连接错误:', error);
        this.eventSource.close();
        this.isLoading = false;

        const lastMessage = this.currentSession.messages[this.currentSession.messages.length - 1];
        lastMessage.streaming = false;

        if (!lastMessage.content) {
          lastMessage.content = '抱歉，AI回复时出现了错误。';
        }
      };

      this.eventSource.addEventListener('complete', () => {
        this.eventSource.close();
        this.isLoading = false;

        const lastMessage = this.currentSession.messages[this.currentSession.messages.length - 1];
        lastMessage.streaming = false;
      });
    },

    scrollToBottom() {
      const container = this.$refs.messagesContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },

    handleFileUpload(event) {
      const files = Array.from(event.target.files);
      const formData = new FormData();

      files.forEach((file, index) => {
        formData.append('files', file); // 与后端字段名保持一致
      });

      const url = "http://localhost:8080/api/chat/upload";
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      };

      this.uploading = true;

      axios.post(url, formData, config)
          .then(response => {
            // 假设后端返回格式为 { success: true, urls: { filename: url } }
            if (response.data.success) {
              this.uploadedFiles.forEach(file => {
                file.status = 'success';
                file.url = response.data.urls[file.name] || 'N/A';
              });
            } else {
              throw new Error('上传成功但无返回URL');
            }
          })
          .catch(error => {
            this.uploadedFiles.forEach(file => {
              file.status = 'error';
              console.error(`文件 ${file.name} 上传失败:`, error);
            });
          })
          .finally(() => {
            this.uploading = false;
            this.progress = 0; // 进度条重置
            event.target.value = ''; // 清空文件输入
          });
      event.target.value = ''; // 重置文件输入
    },

    removeFile(index) {
      this.uploadedFiles.splice(index, 1);
    },

    toggleSearch() {
      this.showSearch = !this.showSearch;
      if (this.showSearch) {
        this.performSearch();
      }
    },

    performSearch() {
      if (!this.searchQuery.trim()) {
        this.searchResults = [];
        return;
      }

      const results = [];
      const query = this.searchQuery.toLowerCase();

      this.chatSessions.forEach((session, sessionIndex) => {
        session.messages.forEach((message, messageIndex) => {
          if (message.content.toLowerCase().includes(query)) {
            results.push({
              sessionIndex,
              messageIndex,
              preview: message.content.substring(0, 100) + (message.content.length > 100 ? '...' : ''),
              timestamp: message.timestamp
            });
          }
        });
      });

      this.searchResults = results;
    },

    navigateToMessage(sessionIndex, messageIndex) {
      this.currentSessionIndex = sessionIndex;
      this.showSearch = false;
      this.searchQuery = '';

      this.$nextTick(() => {
        const messageElement = document.querySelectorAll('.message')[messageIndex];
        if (messageElement) {
          messageElement.scrollIntoView({ behavior: 'smooth' });
        }
      });
    },

    startNewChat() {
      this.chatSessions.push({
        timestamp: new Date(),
        messages: []
      });
      this.currentSessionIndex = this.chatSessions.length - 1;
    },

    switchSession(index) {
      this.currentSessionIndex = index;
    },

    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    formatMessage(content) {
      // 简单的Markdown转换
      return content
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code>$1</code>')
        .replace(/\n/g, '<br>');
    },

    // 切换搜索模式
    toggleSearchMode() {
      this.isSearchMode = !this.isSearchMode;
      if (this.isSearchMode) {
        // 切换到搜索模式时，修改输入框提示
        this.inputMessage = '';
      }
    }
  },
  watch: {
    searchQuery() {
      this.performSearch();
    },
    isSearchMode(newVal) {
      // 根据搜索模式状态修改输入框placeholder
      const textarea = this.$el.querySelector('.message-input');
      if (textarea) {
        textarea.placeholder = newVal ? '输入搜索内容...' : '输入消息...';
      }
    }
  },
  beforeUnmount() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  }
}
</script>

<style scoped>
.ai-chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.chat-header {
  background: white;
  padding: 1rem 2rem;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left h2 {
  margin: 0;
  color: #333;
}

.header-right {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.model-select {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
}

.search-mode-btn {
  padding: 0.5rem;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s ease;
}

.search-mode-btn:hover {
  background: #e9ecef;
}

.search-mode-btn.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.search-btn {
  padding: 0.5rem 1rem;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-btn:hover {
  background: #0056b3;
}

.chat-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.chat-history {
  width: 300px;
  background: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.history-header {
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-header h3 {
  margin: 0;
  font-size: 1rem;
}

.new-chat-btn {
  padding: 0.25rem 0.5rem;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 0.8rem;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem;
}

.history-item {
  padding: 0.75rem;
  margin-bottom: 0.5rem;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.history-item:hover {
  background: #f0f0f0;
}

.history-item.active {
  background: #e3f2fd;
  border-left: 3px solid #2196f3;
}

.session-title {
  display: block;
  font-weight: 500;
  margin-bottom: 0.25rem;
}

.session-time {
  font-size: 0.8rem;
  color: #666;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  background: #fafafa;
}

.message {
  display: flex;
  margin-bottom: 1.5rem;
  max-width: 80%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.ai-message {
  margin-right: auto;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 0.5rem;
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  background: white;
  padding: 1rem;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.user-message .message-content {
  background: #007bff;
  color: white;
}

.thinking-process {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 6px;
  padding: 0.75rem;
  margin-bottom: 1rem;
}

.thinking-header {
  font-weight: bold;
  color: #856404;
  margin-bottom: 0.5rem;
}

.references {
  background: #d1ecf1;
  border: 1px solid #bee5eb;
  border-radius: 6px;
  padding: 0.75rem;
  margin-bottom: 1rem;
}

.references-header {
  font-weight: bold;
  color: #0c5460;
  margin-bottom: 0.5rem;
}

.references ul {
  margin: 0;
  padding-left: 1rem;
}

.references li {
  margin-bottom: 0.25rem;
}

.references a {
  color: #007bff;
  text-decoration: none;
}

.references a:hover {
  text-decoration: underline;
}

.final-answer {
  line-height: 1.6;
}

.final-answer code {
  background: #f8f9fa;
  padding: 0.2rem 0.4rem;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
}

.streaming-indicator {
  margin-top: 0.5rem;
}

.typing-animation {
  display: flex;
  gap: 0.2rem;
}

.typing-animation span {
  width: 6px;
  height: 6px;
  background: #666;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-animation span:nth-child(1) { animation-delay: 0s; }
.typing-animation span:nth-child(2) { animation-delay: 0.2s; }
.typing-animation span:nth-child(3) { animation-delay: 0.4s; }

@keyframes typing {
  0%, 60%, 100% { transform: scale(1); opacity: 0.7; }
  30% { transform: scale(1.5); opacity: 1; }
}

.input-area {
  background: white;
  border-top: 1px solid #e0e0e0;
  padding: 1rem;
}

.input-tools {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
  flex-wrap: wrap;
}

.file-upload-btn {
  padding: 0.5rem;
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
}

.file-upload-btn:hover {
  background: #e9ecef;
}

.uploaded-files {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.file-tag {
  background: #e3f2fd;
  border: 1px solid #bbdefb;
  border-radius: 15px;
  padding: 0.25rem 0.5rem;
  font-size: 0.8rem;
  cursor: pointer;
}

.file-tag:hover {
  background: #bbdefb;
}

.input-container {
  display: flex;
  gap: 0.5rem;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: vertical;
  font-family: inherit;
  font-size: 1rem;
}

.message-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.send-btn {
  padding: 0.75rem 1.5rem;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
}

.send-btn:hover:not(:disabled) {
  background: #0056b3;
}

.send-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.search-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.search-content {
  background: white;
  border-radius: 12px;
  width: 500px;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.search-header {
  padding: 1.5rem;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
}

.close-btn:hover {
  color: #333;
}

.search-input {
  padding: 1rem;
  border: none;
  border-bottom: 1px solid #e0e0e0;
  font-size: 1rem;
}

.search-input:focus {
  outline: none;
}

.search-results {
  flex: 1;
  overflow-y: auto;
  max-height: 300px;
}

.search-result-item {
  padding: 1rem;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-result-item:hover {
  background: #f8f9fa;
}

.result-preview {
  color: #666;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.result-meta {
  font-size: 0.8rem;
  color: #999;
}
</style>
